package com.pan.springboot_markdown.controller;

import com.pan.springboot_markdown.bean.Article;
import com.pan.springboot_markdown.service.ArticleService;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.multipart.MultipartFile;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import java.io.File;
import java.io.IOException;
import java.util.Calendar;
import java.util.HashMap;
import java.util.Map;
import java.util.UUID;

@Controller
public class ArticleController {
    
    @Resource
    private ArticleService articleService;
 
    /**
     * 添加文章
     * @param article
     * @return
     */
    @PostMapping("/addArticle")
    public String addArticle(Article article) {
        articleService.addArticle(article);
        return "editor/editormd";
    }

    //预览控制器
    @GetMapping("/toEditor")
    public String toEditor(){
        return "editor/editormd";
    }


    //文件上传存储问题解决方法
    @PostMapping(value = "/file/upload",produces = "application/json")
    @ResponseBody
    public Map<String,Object> fileUpload(@RequestParam(value = "editormd-image-file", required = true) MultipartFile file, HttpServletRequest request) throws IOException {
        //上传路径保存设置

        //获得SpringBoot当前项目的路径：System.getProperty("user.dir")
        String path = System.getProperty("user.dir")+"/springboot_markdown/upload/";

        //按照月份进行分类：
        Calendar instance = Calendar.getInstance();
        String month = (instance.get(Calendar.MONTH) + 1)+"-month";
        path = path+month;

        File realPath = new File(path);
        if (!realPath.exists()){
            realPath.mkdirs();
        }

        //上传文件地址
        System.out.println("上传文件保存地址："+realPath);

        //解决文件名字问题：我们使用uuid;
        String filename = "pg-"+ UUID.randomUUID().toString().replaceAll("-", "")+".jpg";
        File newfile = new File(realPath, filename);
        file.transferTo(newfile);

        System.out.println("============上传成功");
        //给editormd进行回调
        Map<String,Object> map = new HashMap<>();
        map.put("url","/upload/"+month+"/"+ filename);
        map.put("success", 1);
        map.put("message", "upload success!");
        System.out.println("============上传完成");
        return map;
    }

    //博客分享页面的控制器
    @GetMapping("/show")
    public String show(Model model) {
        Article article = articleService.getArticleById(1);
        model.addAttribute("article", article);
        return "editor/article";
    }


}